#员工月工资统计服务类  flydragon
class Employees::MonthSalaryService
  include HeiPisService

  #employee 员工
  #month 月份字符串(eg:"2017-01")
  def initialize(employee, month)
    @employee = employee
    @month = month
  end

  #执行方法 返回值
  def call
    
    salary_info = month_salaries

    Result.new(salary_info[:base_salary],salary_info[:commission_salary],salary_info[:sum_salary])
  end

  # 获取员工月工资
  def month_salaries

    # 工资信息
    salary_info = {:base_salary => 0,:commission_salary => 0,:sum_salary => 0}

    employee = @employee
    month = @month

    start_date = Date.parse("#{month}-01")
    end_date = Date.parse("#{month}-#{Time.days_in_month(start_date.month,start_date.year)}").end_of_day
    
    #考虑截止时间大于当前时间时,当前时间为截止时间 
    end_date = Time.now if end_date>Time.now 

    # :base_salary, :commission_salary,:sum_salary
    
    employee.salaries.each do |salary|

      salary_type = salary.salary_type

      val_month = 1
      # 员工入职时间
      joined_at = employee.joined_at.to_datetime
      # 如果当前员工未入职,则工资为0
      if joined_at > end_date
        next
      end

      if joined_at>start_date
        start_date = joined_at
      end

      val_month = months_for_dates(start_date,end_date)

      if salary_type=="基本工资"
        salary_info[:base_salary]+=salary.amount*val_month
      elsif salary_type.start_with?("导师")

        employee.employee_of_studios.includes(:teacher).each do |employee_of_studio|
          salary_info[:commission_salary]+=Teachers::SalaryService.call(employee_of_studio.teacher,salary,start_date,end_date)
        end

      elsif salary_type.start_with?("服务顾问_超出指标提成")
        # 所负责学生的营业额
        amount_tmp = fuwuguwen_order_amount(employee,start_date,end_date)

        get_target(employee,month,"服务顾问").each do |target|

          # 超出指标
          if amount_tmp > target.amount
            salary_info[:commission_salary] += (amount_tmp-target.amount)*(salary.amount/100.to_f)
          end
        end
      elsif salary_type.start_with?("运营总监_超出指标提成")
        # 所负责学生的营业额
        amount_tmp = yunyingzongjian_order_amount(employee,start_date,end_date)

        get_target(employee,month,"运营总监").each do |target|

          # 超出指标
          if amount_tmp > target.amount
            salary_info[:commission_salary] += (amount_tmp-target.amount)*(salary.amount/100.to_f)
          end
        end

      elsif salary_type.start_with?("产品总监_超出指标提成")
        # 所负责分店学生的课消
        amount_tmp = chanpinzongjian_amount(employee,start_date,end_date)

        get_target(employee,month,"产品总监").each do |target|

          # 超出指标
          if amount_tmp > target.amount
            salary_info[:commission_salary] += (amount_tmp-target.amount)*(salary.amount/100.to_f)
          end
        end

      elsif salary_type.start_with?("市场总监_超出指标提成")
        # 所负责分店内学生的转化数
        student_count = shichangongjian_count(employee,start_date,end_date)

        get_target(employee,month,"市场总监").each do |target|
          # 超出指标
          if student_count > target.amount
            salary_info[:commission_salary] += (student_count-target.amount)*salary.amount
          end
        end
      elsif salary_type.start_with?("市场专员_超出指标提成")

        # 所负责学生的转化数
        student_count = Student.where(market_employee_id: employee.id,created_at: (start_date..end_date)).count()
        salary_info[:commission_salary] += salary.amount*get_vali_count(student_count,salary.range_min,salary.range_max)
      end

    end

    salary_info[:sum_salary] = salary_info[:base_salary]+salary_info[:commission_salary]
    salary_info
  end


  # 获取服务顾问的营业额
  def fuwuguwen_order_amount(employee,start_date,end_date)

    filter_params = {:employee_id => employee.id,:start_date => start_date,:end_date => end_date}

    sql = %Q{
      select sum(ord.total_price) as total_amount
      from orders ord join students stu on ord.student_id = stu.id
      where stu.service_employee_id = :employee_id 
      and (ord.created_at between :start_date and :end_date) 
    }

    data = 0
    # 获取订单收入
    Order.find_by_sql([sql,filter_params]).each do |record|
      data = record.total_amount
    end
    data
  end



  # 获取运营总监的营业额
  def yunyingzongjian_order_amount(employee,start_date,end_date)

    filter_params = {:employee_id => employee.id,:start_date => start_date,:end_date => end_date}

    sql = %Q{

      SELECT 
          SUM(ord.total_price) AS total_amount
      FROM
          orders ord
              JOIN
          employee_of_studios eos ON ord.studio_id = eos.studio_id
      where (ord.created_at between :start_date and :end_date) 
      and eos.employee_id = :employee_id
    }

    data = 0
    # 获取订单收入
    Order.find_by_sql([sql,filter_params]).each do |record|
      data = record.total_amount
    end
    data
  end


  # 获取产品总监的课消
  def chanpinzongjian_amount(employee,start_date,end_date)

    filter_params = {:employee_id => employee.id,:start_date => start_date,:end_date => end_date}

    sql = %Q{
      SELECT 
          sum(cr.amount) AS total_amount
      FROM
          course_reckons cr
              JOIN
          employee_of_studios eos ON cr.studio_id = eos.studio_id
      where eos.position_name = '产品总监'
      and (cr.created_at between :start_date and :end_date) 
      and eos.employee_id = :employee_id
    }

    data = 0
    # 获取订单收入
    Order.find_by_sql([sql,filter_params]).each do |record|
      data = record.total_amount
    end
    data
  end


  # 获取市场呢总监的学生转化数
  def shichangongjian_count(employee,start_date,end_date)

    filter_params = {:employee_id => employee.id,:start_date => start_date,:end_date => end_date}

    # 课消超出指标
    course_reckon = CourseReckon.where(teacher_id: @teacher.id).sum(:amount).to_f
    sql = %Q{
      SELECT 
          sum(stu.id) AS student_count
      FROM
          students stu
              JOIN
          employee_of_studios eos ON stu.studio_id = eos.studio_id
      where eos.position_name = '市场总监'
      and (stu.created_at between :start_date and :end_date) 
      and eos.employee_id = :employee_id
    }

    data = 0
    # 获取订单收入
    Order.find_by_sql([sql,filter_params]).each do |record|
      data = record.student_count
    end
    data
  end


  def get_target(employee,month,position_name)

    params = {:employee_id => employee.id,:month_of_target=>"#{month}-01",:position_name => position_name}
    sql = %Q{

          SELECT 
              tar.*
          FROM
              employee_of_studios eos
                  JOIN
              targets tar ON eos.id = tar.employee_of_studio_id
          WHERE
              eos.employee_id = :employee_id
          and eos.position_name = :position_name   
          AND tar.month_of_target = :month_of_target
        }

    Target.find_by_sql([sql,params])
  end




  def get_vali_count(count,start_count,end_count)

    # 未达标时,返回有效数量为0
    return 0 if start_count>count

    return (end_count-start_count) > (count-start_count) ? (count-start_count) : (end_count-start_count)
  end




  #内部类,指定结果返回值
  class Result
    attr_reader :base_salary, :commission_salary,:sum_salary

    #base_salary 基本工资
    #commission_salary 提成工资
    #sum_salary 总工资
    def initialize(base_salary, commission_salary, sum_salary)
      @base_salary = base_salary
      @commission_salary = commission_salary
      @sum_salary = sum_salary
    end 

  end



end
